"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource
from flask import jsonify,request,current_app
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from flask_jwt_extended import jwt_required
from apps.API.common.common_time import *
from apps.API.pipeExecutor.models import Analysis

class interfaceQueryResume(Resource):
    @jwt_required() 
    def get(self):
        try:
            username=request.args.get('username')
            run_id=request.args.get("run_id")
            limit=int(request.args.get("limit"))
            page=int(request.args.get("page"))
            query=Analysis.query.order_by(Analysis.run_id.desc())
            if username not in ["admin"]:
                query=query.filter(Analysis.username==username)
            if run_id=='':
                query=query.filter(Analysis.run_status==-1)
                total_length=query.count()
                pagination=query.paginate(page=page, per_page=limit, error_out=False)
                results=[ item.to_dict() for item in pagination.items]
                response=jsonify({"total":total_length,"data":results})
                response.status=202
                return response
            else:
                query=query.filter(Analysis.run_id.ilike(f'%{run_id}%')).filter(Analysis.run_status==-1)
                total_length=query.count()
                pagination=query.paginate(page=page, per_page=limit, error_out=False)
                results=[ item.to_dict() for item in pagination.items]
                response=jsonify({"total":total_length,"data":results})
                response.status=202
                return response
        except Exception as e:
            response=jsonify({})
            response.status=404
            lg.error(e)
            return response
